package com.boesch.electroOffice.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.HttpHeaders;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

public class FileUtils {

	private static final Log log = LogFactoryUtil.getLog(FileUtils.class);

	public static void removeDirectory(File folder) {
		// check if folder file is a real folder
		if (folder.isDirectory()) {
			File[] list = folder.listFiles();
			if (null != list) {
				doRemoveFiles(list);
			}
			if (!folder.delete()) {
				log.debug("Folder was not deleted: " + folder);
			}
		}
	}

	/**
	 * @param list
	 */
	private static void doRemoveFiles(File[] list) {
		File tmpFile = null;
		for (File element : list) {
			tmpFile = element;
			if (tmpFile.isDirectory()) {
				removeDirectory(tmpFile);
			}
			tmpFile.delete();
		}
	}

	public static String getMimeType(byte[] input) {
		ByteArrayInputStream bai = null;
		Metadata metadata = new Metadata();
		try {
			bai = new ByteArrayInputStream(input);
			ContentHandler contenthandler = new BodyContentHandler();
			Parser parser = new AutoDetectParser();
			parser.parse(bai, contenthandler, metadata, null);
		} catch (IOException e) {
			log.error("Error retrieving MimeType", e);
		} catch (SAXException e) {
			log.error("Error retrieving MimeType", e);
		} catch (TikaException e) {
			log.error("Error retrieving MimeType", e);
		} finally {
			if(null != bai){
				try {
					bai.close();
				} catch (IOException e) {
					log.error("Error on closing ByteArrayInputStream.", e);
				}
			}
		}
		return metadata.get(HttpHeaders.CONTENT_TYPE);
	}

	@Override
	public String toString() {
		return "FileUtils [getClass()=" + getClass() + ", hashCode()="
				+ hashCode() + ", toString()=" + super.toString() + "]";
	}	
}
